package qdu.edu.cn.servlet;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import qdu.edu.cn.jdbc.MySQLDataBaseConnection;
import qdu.edu.cn.storm.client.DRPCSearchWebClient;

//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

//@WebServlet("/SelectMySQL")
public class SelectMySQL extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        resp.setContentType("text/html;charset=UTF-8");
        String words = multipleChineseCharactersAreSplicedIntoOneSentence(req.getParameter("word"));
        PrintWriter writer = resp.getWriter();

        String hyperlink = new DRPCSearchWebClient(req.getRequestedSessionId() + ',' + req.getParameter("word")).getResult();
        String[] split = hyperlink.split(" ");
        List<String> list = new ArrayList<>(Arrays.asList(split));
        list.remove(0); // 移除第一个元素，值为""空，RedisStoreRequestListBolt类中hyperlinks初始值为""导致的
        String jsonHyperlinks = JSONArray.toJSONString(list);
        Map<String, String> map = new HashMap<>();
        map.put("words", words);
        map.put("hyperlinks", jsonHyperlinks);
        // 转换后，含有转义字符，需要替换掉
        String json = JSONObject.toJSONString(map);
        writer.print(json);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doGet(req, resp);
    }

    private String select(String word) {
        MySQLDataBaseConnection mysql = new MySQLDataBaseConnection();
        String words = mysql.select(word, 5);
        mysql.closeConnection();
        return words;
    }

    // TODO 空格分隔，批量匹配生成一句话
    public String multipleChineseCharactersAreSplicedIntoOneSentence(String string) {
        String[] split = string.split("[^\\u4e00-\\u9fa5]+");

        String result;
        Map<String, String> maps = new HashMap<>();
        // 查询
        for (String split_part: split) {
            maps.put(split_part, select(split_part));
        }

        if (split.length <= 1) {
            return select(string);
        }
        // 拼接
        result = maps.get(split[0]);
        for ( int i=1; i<maps.size(); i++) {
            result = splicing(result, maps.get(split[i]));
        }

        return result;
    }

    public String splicing (String value1, String value2) {
        String sentence;
        // 如果value1中含有key2，那就将value1中key2及其后的部分用value2替换
        sentence = value1 + "，" + value2;

        return sentence;
    }
}
